
# sysmon.sh      磁盘 / 内存 / CPU 监控报警
# 放/opt/monitor ，chmod +x ，systemctl enable sysmon

# 可调 
DISK_WARN=85        # 磁盘使用率报警阈值 %
MEM_WARN=80         # 内存使用率报警阈值 %
CPU_WARN=70         # CPU 使用率报警阈值 %
LOG_DIR="/var/log/monitor"

mkdir -p "$LOG_DIR"
LOG_FILE="$LOG_DIR/sysmon-$(date +%F).log"

log() {
    echo "$(date '+%F %T') $*" | tee -a "$LOG_FILE" | logger -t sysmon
}

check_disk() {
    df -P | awk -v w=$DISK_WARN 'NR>1 && int($5)>=w {
        printf "DISK-WARN %s %s%% mounted on %s\n", $1, $5, $6
    }'
}

check_mem() {
    awk -v w=$MEM_WARN '
    /^MemTotal/  {total=$2}
    /^MemAvailable/ {avail=$2}
    END {
        used=int((total-avail)*100/total);
        if (used>=w) print "MEM-WARN " used "%"
    }' /proc/meminfo
}

check_cpu() {
    # 1 秒采样
    read cpu1 _ </proc/stat
    sleep 1
    read cpu2 _ </proc/stat
    set -- $cpu1 $cpu2
    idle1=$5 idle2=$11
    total1=$(($1+$2+$3+$4+$5+$6+$7+$8+$9+$10))
    total2=$(($12+$13+$14+$15+$16+$17+$18+$19+$20+$21))
    cpu_usage=$((100*(total1-total2-idle1+idle2)/(total1-total2)))
    [ $cpu_usage -ge $CPU_WARN ] && echo "CPU-WARN ${cpu_usage}%"
}

main() {
    check_disk | while read line; do log "$line"; done
    check_mem  | while read line; do log "$line"; done
    check_cpu  | while read line; do log "$line"; done
}

main